package com.yuanxiao.mvcframework.servlet;

import com.yuanxiao.mvcframework.annotations.*;
import com.yuanxiao.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LaDispatcherServlet  extends HttpServlet {
    private Properties properties = new Properties();
    private List<String> classNames=new ArrayList<>();//缓存扫描到的类的全限定名
    private Map<String,Object> ioc =new HashMap<String,Object>();
    //private Map<String,Method> handlerMapping=new HashMap<>();//存储URL和method的映射关系
    private List<Handler> handlerMapping=new ArrayList<>();
    @Override
    public void init(ServletConfig config) throws ServletException {
        //1加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2扫描相关的类.和注解
        doScan(properties.getProperty("scanPackage"));
        //3初始化bean(实现IOC容器)
        doInstance();

        //4实现依赖注入
        doAutoWired();

        //5构造一个 handlerMapping处理器映射器,将配置好的ul和method建立映射关系
        initHandlerMapping();
        System.out.println("拉勾mvc  初始化完成");
        //等待请求进入,处理请求
    }
    //构造一个 handlerMapping处理器映射器 最关键的环节
    //目的 将url同Controller的方法的映射
    private void initHandlerMapping() {
        //容器中是否有对象
        if(ioc.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();
            if(!aClass.isAnnotationPresent(LagouController.class)){
                continue;
            }
            String baseUrl="";
            if(aClass.isAnnotationPresent(LagouRequestMapping.class)){
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl=annotation.value(); //  "/demo"
            }
            String[] value={};
            if(aClass.isAnnotationPresent(Security.class)){
                Security security = aClass.getAnnotation(Security.class);
                value = security.value();//先判断是否在类上有权限
            }

            //获取方法
            String methodUrl="";
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                if(!method.isAnnotationPresent(LagouRequestMapping.class)){continue;}
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                methodUrl=annotation.value();// "/query"
                String url=baseUrl+methodUrl;
               //把method所有信息及url封装为handle
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                //处理计算参数位置信息

                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType()==HttpServletResponse.class){
                       //如果是这两个对象， 那么参数名称写HttpServletRequest ，HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
                    }else {
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }

                if(method.isAnnotationPresent(Security.class)){
                    Security security = method.getAnnotation(Security.class);
                    String[] value1 = security.value();//再判断是否在方法上有权限,当方法上有权限的时候,以方法为准
                    value= value1.length==0?value:value1;
                }

                //设定访问权限
                handler.setUsers(value);

                //建立url和方法的映射关系
                handlerMapping.add(handler);
            }
        }



    }

    //实现依赖注入
    private void doAutoWired() {
        //容器中是否有对象
        if(ioc.isEmpty()){return;}
        //有对象,再进行依赖注入处理

        //遍历IOC中所有对象,查看对象中的字段,是否有@lagouAutowired注解,.有则需要维护依赖注入关系
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            //遍历判断处理
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                if(!declaredField.isAnnotationPresent(LagouAutowired.class)){
                    continue;
                }
                //有该注解
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String beanName = annotation.value();
                if("".equals(beanName.trim())){
                    //没有配置具体的beanid 那就需要根据当前字段类型注入(接口注入)
                    beanName = declaredField.getType().getName();
                }
                //开启复制
                declaredField.setAccessible(true);
                try {
                    //给entry.getValue()这个对象的declaredField 属性  赋值:ioc.get(beanName)
                    declaredField.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    //ioc容器
    //基于classNames缓存类的全限定名,以及反射技术,完成对象创建和管理
    private void doInstance()  {
        if (classNames.size()==0)return;
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);//controller...

                Class<?> aClass = Class.forName(className);
                //区分controller,区分service

                if(aClass.isAnnotationPresent(LagouController.class)){
                    //controller的id不做过多处理 就用类的首字母小写作为id保存到ioc
                    String simpleName = aClass.getSimpleName();//DemoController
                    String lowerFirstSimpleName = lowerFirst(simpleName);//demoController
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName,o);
                }else if(aClass.isAnnotationPresent(LagouService.class)){
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    String beanName = annotation.value();
                    if(!"".equals(beanName.trim())){//有名字 用取的名字
                    }else {
                        //如果没有指定,就用类名首字母小写
                        beanName = lowerFirst(aClass.getSimpleName());
                    }
                    ioc.put(beanName,aClass.newInstance());
                    //service层往往是有接口的,. 面向接口开发,此时再以接口名为id,放入一份对象,便于后去根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        //以接口的全限定类名作为ID放入
                        ioc.put(anInterface.getName(),aClass.newInstance());
                    }
                }else {
                    continue;
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }





    }

    public String lowerFirst(String str){
        char[] chars = str.toCharArray();
        if('A'<= chars[0] && chars[0]<='Z'){
            chars[0]+=32;
        }
        return String.valueOf(chars);
    }

    //扫描类com.yuanxiao.mvcframework
    private void doScan(String scanPackage) {
        //获取 classpath所在的磁盘路径.在拼接 的到包路径
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();

        for (File file : files) {
            if(file.isDirectory()){ //子package
                //递归
                doScan(scanPackage+"."+file.getName());
            }else if(file.getName().endsWith(".class")){
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //接收处理请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //处理请求

       //反射调用,需要传入对象,参数.此处无法完成,没有把对象缓存起来,也没有参数
       // Method method = handlerMapping.get((requestURI));//获取反射的方法
        //根据url获取到能处理当前请求的handle，
        Handler handler = getHandler(req);
        if(handler==null){
            resp.getWriter().write("404 not found");
            return;
        }

        String[] users = handler.getUsers();//为空则全部可以访问
        if(users.length!=0){//不为空开始判断访问人员是否在权限数组中
            List<String> strings = Arrays.asList(users);
            if(!strings.contains(req.getParameter("username"))){
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write("用户没有访问权限");
                return;
            }
        }
        //参数绑定
        //获取所有参数类型数组，这个数组的长度就是我们要传入的args的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //根据上述数字长度创建一个新的数组（参数数组）
        Object[] paraValues= new Object[parameterTypes.length];
        //以下就是为了参数数组中塞值，顺序保证和方法形参一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        //遍历所有requst中所有参数
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
        //name=1&name=2
            String value = StringUtils.join(param.getValue(), ",");//如同 1 ，2
            //如果参数和方法中的参数匹配上了。， 填充数据
            if(!handler.getParamIndexMapping().containsKey(param.getKey())){
                continue;
            }
            paraValues[handler.getParamIndexMapping().get(param.getKey())]=value;//把前台传递过的参数值填充到对应的位置去
        }
        Integer requestinteger = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestinteger]=req;

        Integer responseinteger = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseinteger]=resp;


        //最终调用handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()){return null;}

        //获取url
        String requestURI = req.getRequestURI();
        for (Handler handler : handlerMapping) {

            Matcher matcher = handler.getPattern().matcher(requestURI);
            if(!matcher.matches()){continue;}
            return handler;
        }

        return null;
    }


}
